Uec3.StoreWindow = Ext.extend(Ext.app.Module, {
	id : 'store',
	type : 'common/store',

	/**
	 * Initialize this module. This function is called at startup (page
	 * load/refresh).
	 */
	init : function(initParams) {
	},

	paramsCollection : new Ext.util.MixedCollection(true),

	getParamsByKey : function(key) {
		return this.paramsCollection.get(key);
	},

	browseStore : function(rowIndex) {

		var store_ds = this.getParamsByKey('store_ds');

		var store_form = this.getParamsByKey('store_form');

		var store_win = this.getParamsByKey('store_win');
		
		var record = store_ds.getAt(rowIndex);

		store_form.getForm().loadRecord(record);
		
		store_win.show();

		store_win.buttons[0].hide();

		store_win.buttons[1].hide();

		store_win.setTitle('浏览仓库-按Esc退出');

		var maskTopField = this.getParamsByKey('maskTopField');
			
		maskTopField.show();

	},

	editStore : function(rowIndex) {

		var store_ds = this.getParamsByKey('store_ds');

		var store_form = this.getParamsByKey('store_form');

		var store_win = this.getParamsByKey('store_win');

		var record = store_ds.getAt(rowIndex);

		store_form.getForm().loadRecord(record);
		
		store_win.show();

		store_win.buttons[0].show();
		store_win.buttons[1].show();

		store_win.buttons[0].setText('更新');

		store_win.setTitle('编辑仓库-按Esc退出');

	},

	deleteStore : function(rowIndex) {

		var store_ds = this.getParamsByKey('store_ds');
        var store_grid = this.getParamsByKey('store_grid');
        var record = store_ds.getAt(rowIndex);

		Ext.Msg.confirm('信息', '确定要删除?', function(btn) {
					if (btn == 'yes') {

						store_grid.loadMask.show();

						var storeId = record.get('id');
						Ext.Ajax.request({
									url : Uec3.App.Constants.homeUrl
											+ '/store/base!delete.do',
									success : function(res) {

										var result = res.responseText;

										if (!result) {

											store_ds.remove(record);
											// store_grid.getView().refresh();
											store_ds.reload();
											store_grid.loadMask.hide();
											Ext.Msg.alert("提示", "删除成功");

										} else {
											store_grid.loadMask.hide();
											Ext.Msg
													.alert(
															"提示",
															Ext.decode(result).failure);
										}
									},

									failure : function(res) {
										store_grid.loadMask.hide();
										Ext.Msg.alert("提示", '网络异常,请重先连接');

									},

									params : {
										id : storeId
									}

								});

					}
				});
	},
	revertStore:function(rowIndex){
		var store_ds = this.getParamsByKey('store_ds');
		var store_grid = this.getParamsByKey('store_grid');
        var record = store_ds.getAt(rowIndex);
		var storeId = record.get('id');
		Ext.Ajax.request({
					url : Uec3.App.Constants.homeUrl
							+ '/store/base!revertStore.do',
					success : function(res) {

						var result = res.responseText;

						if (!result) {

							store_ds.remove(record);
							// store_grid.getView().refresh();
							store_ds.reload();
							store_grid.loadMask.hide();

						} else {
							store_grid.loadMask.hide();
							Ext.Msg
									.alert(
											"提示",
											Ext.decode(result).failure);
						}
					},

					failure : function(res) {
						store_grid.loadMask.hide();
						Ext.Msg.alert("提示", '网络异常,请重先连接');

					},

					params : {
						id : storeId
					}

				});
		
	},
	getComponents : function(module) {

		var departmentStore_ds;
		var store_ds;
		var store_grid;
		var store_win;
		var store_form;
		var store_ajax;
		var store_departmentLookUp;
        var keymap;
        var navigation;
		function renderDesc(value, cellmeta, record, rowIndex, columnIndex,
				store){
			var str;
			
			var isDelete = record.get("isDelete");
			var i=record.get("isDefault");
			if (module.app.hasPermission(16)) {

				if (isDelete==1) {

					str = "<a style='font-size:12px' href='javascript:Ext.CUR_APP.getModule(\"store\").browseStore("
							+ rowIndex
							+ ");'>查看</a>|"
							+ "<a style='font-size:12px;margin-left:12px' href='javascript:Ext.CUR_APP.getModule(\"store\").revertStore("
							+ rowIndex + ");'>恢复</a>|"

				} else {
					
					if(i==1){
						
						str = "<a style='font-size:12px' href='javascript:Ext.CUR_APP.getModule(\"store\").browseStore("
							+ rowIndex
							+ ");'>查看</a>|"
							+ "<a style='font-size:12px;margin-left:12px'   href='javascript:Ext.CUR_APP.getModule(\"store\").editStore("
							+ rowIndex
							+ ");'>编辑</a>|"
						
					}else{

					str = "<a style='font-size:12px' href='javascript:Ext.CUR_APP.getModule(\"store\").browseStore("
							+ rowIndex
							+ ");'>查看</a>|"
							+ "<a style='font-size:12px;margin-left:12px'   href='javascript:Ext.CUR_APP.getModule(\"store\").editStore("
							+ rowIndex
							+ ");'>编辑</a>|"
							+ "<a style='font-size:12px;margin-left:12px' href='javascript:Ext.CUR_APP.getModule(\"store\").deleteStore("
							+ rowIndex + ");'>删除</a>|"
					}
				}

			} else if (module.app.hasPermission(15)) {

				str = "<a style='font-size:12px' href='javascript:Ext.CUR_APP.getModule(\"store\").browseStore("
						+ rowIndex + ");'>查看</a>|"

			};
			return str;
		}
		var getAndRestoreStore = function() {

			departmentStore_ds = new Ext.data.Store({
						proxy : new Ext.data.HttpProxy({
									url : Uec3.App.Constants.homeUrl
											+ '/department/base!findByCompanyId.do'
								}),
						reader : new Ext.data.JsonReader({
									root : 'root',
									fields : [{
												name : 'id'
											}, {
												name : 'name'
											}, {
												name : 'pyCode'
											}]
								})
					});

			store_ds = new Ext.data.Store({
						// proxy: new Ext.data.MemoryProxy(myData),
						proxy : new Ext.data.HttpProxy({
									url : Uec3.App.Constants.homeUrl
											+ '/store/base!query.do'
								}),
						baseParams : {
							start : 0,
							limit : 20
						},
						reader : new Ext.data.JsonReader({
									totalProperty : 'totalProperty',
									root : 'root'
								}, [

										{
											name : 'id'
										}, {
											name : 'companyId'
										}, {
											name : 'departmentId'
										}, {
											name : 'departmentName'
										},{
											name : 'isDefault',
											type:'int'
										}, {
											name : 'name'
										}, {
											name : 'gmtCreate',
											type : 'string'
										}, {
											name : 'gmtModify',
											type : 'string'
										}, {
											name : 'isDelete',
											type : 'int'
										}

								]),
						remoteSort : true,

						// 默认排序字段
						sortInfo : {
							field : "id",
							direction : "asc"
						}

					});

		};

		var componentInitsStore = function() {

			store_departmentLookUp = new Ext.form.LookupBox2({
						store : departmentStore_ds,
						displayField : 'name',
						lookupField : 'pyCode',
						valueField : 'id',
						hiddenName : 'departmentId',
						allowBlank : false,
						typeAhead : false,
						mode : 'local',
						emptyText : '请选择部门...',
						selectOnFocus : true,
						queryDelay : 10,
						typeAheadDelay : 10,
						pageSize : 6,
						width:200,
						autoDestory : true,
						queryParam : 'keyword',
						app : module.app,
						triggerTags : [{
									moduleId : 'departmentQuery',
									triggerClass : 'x-form-search-trigger'
								}, {
									moduleId : 'departmentAdd'
								}],

						listeners : {
							select : function() {

							}
						}
					});
			// 为了再loadRecord的使用能找到数据
			departmentStore_ds.load({
						params : {
							start : 0,
							limit : 6
						}
					});
			// 初始化目录
			var tab = new Ext.TabPanel({
				width : 225,
				region : 'center',
				activeTab : 0,
				items : [{
							title : '目录',
							layout : 'accordion',
							items : [{
										collapsible : true,
										title : '删除记录',
										xtype : 'treepanel',
										width : 225,
										lines : false,
										height : document.body.clientHeight
												* 1.0,
										autoScroll : true,
										split : true,
										loader : new Ext.tree.TreeLoader(),
										root : new Ext.tree.AsyncTreeNode({
													expanded : true,
													children : [{
																text : '全部',
																value : '2',
																leaf : true
															}, {
																text : '未删除',
																value : '0',
																leaf : true
															}, {
																text : '已删除',
																value : '1',
																leaf : true
															}]
												}),
										rootVisible : false,
										listeners : {
											click : function(child) {

												var v = {
													isDelete : child.attributes.value
												};
												var jsonAll = Ext.encode(v);
												store_ds.baseParams = {
													start : 0,
													limit : 20,
													jsonAll : jsonAll
												}
												store_ds.reload();
											}
										}
									}]
						}]
			});

			navigation = new Ext.Panel({
						title : '导航与搜索',
						region : 'west',
						split : true,
						width : 225,
						minSize : 225,
						maxSize : 225,
						collapsible : true,
						lines : false,
						layout : 'fit',
						margins : '3 0 3 3',
						cmargins : '3 3 3 3',
						items : [tab]
					});
			
			
			
			
			// 初始化receiptAddress表格对象

			var store_colModel = new Ext.grid.ColumnModel([
					new Ext.grid.RowNumberer(),

					{
						header : "操作",
						width : 120,
						dataIndex : 'act',
						renderer : renderDesc
							/**module.moduleActionRenderer([{
							func:'browseStore',
							desc:'查看',
							permission:15
						},{
							func:'editStore',
							desc:'编辑',
							permission:16
						},
						{
							func:'deleteStore',
							desc:'删除',		
							isShow:function(value,meta,record){
								 
							    var i=record.get("isDefault");
							     
							     if(i==1){
							     
							     return false;
							     
							  }
							  return true;
							},
							permission:16
						}])*/
					}, {
						header : "仓库名称",
						width : 80,
						sortable : true,
						dataIndex : 'name'
					}, {
						header : "部门",
						width : 80,
						dataIndex : 'departmentName'
					}, {
						header : "创建时间",
						width : 100,
						dataIndex : 'gmtCreate'
					}, {
						header : "修改时间",
						width : 100,
						dataIndex : 'gmtModify'
					}

			]);

			// create the Grid
			store_grid = new Ext.grid.GridPanel(

			{
						// title:'仓库信息列表',
						region : 'center',
						iconCls : 'icon-grid',
						enableColumnMove : false,
						enableColumnMoveResize : false,
						stripeRows : true,
						hight : 500,
						loadMask : {
							msg : "...加载数据中"
						},
						store : store_ds,
						cm : store_colModel,
						sm : new Ext.grid.RowSelectionModel({
									singleSelect : true
								}),
						viewConfig : {
							forceFit : true,
							columnsText : '显示的列',
							scrollOffset : 20,
							sortAscText : '升序',
							sortDescText : '降序'
						},
						tbar : new Ext.app.ModuleToolbar(['-', {
							text : '增加',
							permission:16,
							icon : Uec3.App.Constants.deskUrl
									+ "/resources/images/default/dd/drop-add.gif",
							// cls: "x-btn-text-icon",
							handler : function() {

								if (!(store_form.getForm().getEl())) {
									store_form.getForm().reset();
								} else {
									store_form.getForm().getEl().dom.reset();
								}
								store_form.getForm().findField('id')
										.setValue('');
								store_win.buttons[0].show();
								store_win.buttons[1].show();
								store_win.show(this);
								store_win.buttons[0].setText('增加');
								store_win.setTitle('增加仓库-按Esc退出');
								store_form.setDisabled(false);
							}
						}]),
						bbar : new Ext.PagingToolbar({
									pageSize : 20,
									store : store_ds,
									display : true,
									displayInfo : true,
									displayMsg : '第 {0} - {1} 条  共 {2} 条',
									emptyMsg : "没有记录",
									items : [/**
									 * '-', { pressed: true,
									 * enableToggle:true, text:
									 * 'Show Preview', cls:
									 * 'x-btn-text-icon details',
									 * toggleHandler: function(btn,
									 * pressed){ var view =
									 * store_grid.getView();
									 * view.showPreview = pressed;
									 * view.refresh(); } }
									 */
									]
								})

					});

		//	store_ds.load();

			// 初始化表单对象
			store_form = new Ext.form.FormPanel({
						labelAlign : 'right',
						labelWidth : 60,
						// title:客户档案,
						frame : true,
						width : 800,
						autoHeight : true,
						url : '',
						items : [{
									layout : 'column',
									items : [{
												columnWidth : .5,
												layout : 'form',
												defaultType : 'textfield',
												items : [{
															name : 'id',
															fieldLabel : 'ID',
															xtype : 'hidden'
														}, {
															name : 'companyId',
															fieldLabel : '公司ID',
															xtype : 'hidden'
														},
														/**
														 * { name:
														 * 'companyName',
														 * fieldLabel:'公司名称',
														 * readOnly:true },
														 */

														store_departmentLookUp

												]
											},

											{
												columnWidth : .5,
												layout : 'form',
												defaultType : 'textfield',
												items : [

												{
															name : 'name',
															fieldLabel : '仓库名称',
															width:200,	
															allowBlank:false,
															blankText:"仓库名称必须填写",
														    maxLength:"30",
															maxLengthText:"最大长度为30位"
														}]
											}]
								}]
					});

			store_ajax = new Ext.data.Connection();

			var desktop = module.app.getDesktop();
			// 初始化window对象
			store_win = desktop.createWindowNoTask({
						layout : 'fit',
						// constraitHeader:true,
						closeAction : 'hide',
						width : 660,
						autoScroll : true,
						autoHeight : true,
						title : '增加仓库-按Esc退出',
						collapsible : true,
						constrait : true,
						modal : true,
						draggable : true,
						plain : true,
						//manager : desktop.windows,
						header : true,
						resizable : true,
						minimizable:false,
						maximizable:false,
						items : [store_form],
						buttons : [{
							text : '保存',
							iconCls:"icon-save",
							handler : function() {

								if (!store_form.getForm().isValid()) {
									Ext.Msg.alert("提示", "请填写必须项");
									return;

								}

								var formValues = store_form.getForm()
										.getValues();
								var jsonAll = Ext.encode(formValues);

								store_ajax.request({
											url : Uec3.App.Constants.homeUrl
													+ '/store/base!save.do',
											success : function(res) {

												var result = Ext
														.decode(res.responseText);
												if (result.success == "OK") {

													store_win.hide();

													store_ds.reload();

												} else {

													Ext.Msg.alert("提示",
															result.failure);
													store_ds.reload();
												}
											},

											failure : function(res) {

												Ext.Msg.alert('失败',
														"网络出现异常，请重先连接");

											},

											params : {
												jsonAll : jsonAll
											}

										});

							}

						}, {
							text : '关闭',
                            iconCls:"icon-close",
							handler : function() {

								store_win.hide();

							}

						}],

						buttonAlign : 'center'

					});

		};

		var controlStoreEvent = function() {

			store_ajax.on('beforerequest', function() {

						Ext.MessageBox.wait("保存数据中...", "提示");
					});

			store_ajax.on('requestcomplete', function() {

						Ext.MessageBox.hide();
					});

			store_win.on("show",function(){
				keymap = new Ext.KeyMap(store_win.id, {
				    key: 13, // or Ext.EventObject.ENTER
				    fn: function(){
			
					if (!store_form.getForm().isValid()) {
						Ext.Msg.alert("提示", "请填写必须项");
						return;

					}

					var formValues = store_form.getForm()
							.getValues();
					var jsonAll = Ext.encode(formValues);

					store_ajax.request({
								url : Uec3.App.Constants.homeUrl
										+ '/store/base!save.do',
								success : function(res) {

									var result = Ext
											.decode(res.responseText);
									if (result.success == "OK") {

										store_win.hide();

										store_ds.reload();

									} else {

										Ext.Msg.alert("提示",
												result.failure);
										
										store_ds.reload();

									}
								},

								failure : function(res) {

									Ext.Msg.alert('失败',
											"网络出现异常，请重先连接");

								},

								params : {
									jsonAll : jsonAll
								}

							});
					
				},
				    scope: store_win
				});	
				
	    		var maskTopField = new Ext.LoadMaskJUPIT(store_form.id);
	    		module.paramsCollection.add("maskTopField", maskTopField);
			},this,{singe:true});
			

			store_win.on("hide",function(){
					
				keymap.setDisabled(true);
	    		var maskTopField = module.getParamsByKey("maskTopField");
	    		if(maskTopField)maskTopField.hide();
	    		
			},this);
			
			
			
			/**
			 * store_ds.on('load', function() { var me = this;
			 * 
			 * var records = me.getRange(); Ext.each(records, function(record) {
			 * 
			 * var rowId = me.indexOf(record);
			 * 
			 * Ext.get('browseStore_'+ rowId).on('click', function(e) {
			 * 
			 * browseStore(rowId);
			 * 
			 * });
			 * 
			 * Ext.get('editStore_'+ rowId).on('click', function(e) {
			 * 
			 * 
			 * editStore(rowId);
			 * 
			 * });
			 * 
			 * alert(Ext.getDom('browseStore_'+ rowId)); Ext.get('deleteStore_'+
			 * rowId).on('click',
			 * 
			 * function(e) {
			 * 
			 * deleteStore(rowId);
			 * 
			 * }); })
			 * 
			 * });
			 */

		};

		getAndRestoreStore();

		componentInitsStore();

		controlStoreEvent();

		this.paramsCollection.add("store_ds", store_ds);
		this.paramsCollection.add("store_form", store_form);
		this.paramsCollection.add("store_win", store_win);
		this.paramsCollection.add("store_grid", store_grid);

		return [navigation, store_grid];

	},
	initEvent:function(){
		var module=this;
		var win=module.getParamsByKey("win");
		win.on('show',function(){
			this.getParamsByKey("store_ds").load({
				 callback: function(records,options,success){
		         
		         if(success){
		        	 
		        	 //Ext.Msg.alert('提示',"加载数据成功");
		         }else{
		        	 
		        	 
		        	 Ext.Msg.alert('提示',"服务器正在升级中...请稍候再试");
		         }			  
			
		 }			
	
	});
		},module,{single:true});
	},
	/**
	 * Create this modules window here.
	 */
	createWindow : function() {
		var desktop = this.app.getDesktop();
		var win = desktop.getWindow('store');
		var module=this;
		if (!win) {
			win = desktop.createWindow({
						id : 'store',
						title : '仓库列表',
						width : document.body.clientWidth * 1.0,
						height : document.body.clientHeight * 1.0,
						iconCls : 'acc-icon',
						shim : false,
						animCollapse : false,
						constrainHeader : true,
						maximizable : true,
						maximized : true,
						taskbuttonTooltip : "仓库列表",
						layout : "border",
						resizable : true,
						tools : [{
									id : 'refresh',
									handler : Ext.emptyFn,
									scope : this
								}],
						items : [this.getComponents(module)]
					}); 
			module.paramsCollection.add("win",win);
			module.initEvent();

		}
		win.show();

	}
});